<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>获取屏幕刷新率</title>
</head>

<body>
  <h3 id="frame"></h3>
  <script>
    /**
     * 原理就是采样50次requestAnimationFrame，计算时间差，取后10次时间差的平均
     */
    const itemDiffrences = arr => arr.map((item, index) => item - arr[index - 1]).slice(-10);
    const meanAverage = arr => arr.reduce((prev, current) => prev + current / arr.length, 0);
    const measureRefreshRate = ({ sampleCount }) => new Promise(resolve => {
      const times = [window.performance.now()]

      const eachFrame = () => {
        times.push(window.performance.now())

        if (times.length - 1 < sampleCount) {
          requestAnimationFrame(eachFrame)
        } else {
          resolve(Math.round(1000 / meanAverage(itemDiffrences(times))))
        }
      }

      requestAnimationFrame(eachFrame)
    })
    measureRefreshRate({ sampleCount: 50 }).then((res) => {
      document.querySelector('#frame').innerHTML = `刷新率为:${res}`;
    })
  </script>
</body>

</html>